﻿using Daemon.Common.Exceptions;
using Daemon.Model;
using Daemon.Repository.Contract;
using Daemon.Service.Contract;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Daemon.Service
{
	public class TakeAwayUserBookService : ITakeAwayUserBookService
	{

		private readonly ITakeAwayUserBookRepository _takeAwayUserBookRepository;

		private readonly ITakeAwayBoardAreaRepository _takeAwayBoardAreaRepository;

		private readonly object _locker;

		public TakeAwayUserBookService(ITakeAwayUserBookRepository takeAwayUserBookRepository
			, ITakeAwayBoardAreaRepository takeAwayBoardAreaRepository)
		{
			_takeAwayUserBookRepository = takeAwayUserBookRepository;
			_takeAwayBoardAreaRepository = takeAwayBoardAreaRepository;
			_locker = new object();
		}

		public TakeAwayUserBook BookBoard(TakeAwayUserBook entity)
		{
			lock (_locker)
			{
				var areaBoardCount = _takeAwayBoardAreaRepository.FindAll().FirstOrDefault(r => r.Id == entity.BoardTypeId && r.Status == 1);
				if (areaBoardCount == null)
				{
					throw new BusinessException((int)HttpStatusCode.Forbidden, "");
				}

				var boradCountIndex = $"boardCount_{areaBoardCount.Id}";
				var currentBoardCount = RedisHelper.Get<string>(boradCountIndex);
				if (string.IsNullOrEmpty(currentBoardCount))
				{
					currentBoardCount = areaBoardCount.BoardCount.ToString();
					RedisHelper.Set(boradCountIndex, areaBoardCount.BoardCount.ToString());
				}

				var bookCountIndex = $"bookCount_{entity.BoardTypeId}";
				var bookedCount = RedisHelper.Get<string>(bookCountIndex);
				if (string.IsNullOrEmpty(bookedCount))
				{
					bookedCount = _takeAwayUserBookRepository.FindAll().Count(r => r.BoardTypeId == entity.BoardTypeId && r.Status == 0).ToString();
					RedisHelper.Set(bookCountIndex, bookedCount);
				}

				if (Convert.ToInt32(bookedCount) > Convert.ToInt32(currentBoardCount))
				{
					throw new BusinessException((int)HttpStatusCode.Forbidden, "");
				}

				entity.AddTime = DateTime.Now;
				entity.Status = 0;
				return _takeAwayUserBookRepository.AddByDBContext(entity);
			}
		}
	}
}
